<?php
	require '../../include/library.inc.php';
	require '../../include/admin_login.inc.php';
	
	$_SESSION['dir'] = '../albums/'.intval($_GET['album_id']).'/';
	if(!is_dir($_SESSION['dir'])) mkdir($_SESSION['dir'], 0755); 
	$id = intval($_GET['album_id']);
			
	if (!isset($_POST['is_submitted'])) {
		$_POST['is_submitted'] = '';
	}
	if (!isset($error_message)) {
		$error_message = '';
	}	
	
	
	if($_POST["redirect"] || $_SESSION['redirect'] ){
		if($_POST["redirect"]) $redirect = $_POST["redirect"];
		if($_SESSION['redirect']){ 
			$redirect = $_SESSION['redirect'];
			unset($_SESSION['redirect']);
		}
	}else{
		   $redirect = $_SERVER['HTTP_REFERER'];	
		 }	
	
	
	if ($_POST['is_submitted']) {
		$error_message = '';
		$redirect = $_POST["redirect"];
    
		$sql = 'SELECT lang_id,Name,code FROM language WHERE published';
		$result_lang = query($sql);
		
		while ($row_lang = mysql_fetch_object($result_lang)) {
					$em = $row_lang->lang_id;
					eval('$name =  $_POST[\'title_'.$em.'\'];');
					if (!$name)  $error_message .= 'Не е въведено заглавие на '.$row_lang->Name.'<br/>';
					
		}
		
		
		
		if (!$_POST['sef_url'])  $error_message .= 'Не е въведен SEF URL<br/>';
			elseif(!preg_match('/^[0-9A-Za-z\p{Cyrillic}\-\_]+$/u', $_POST['sef_url'])) $error_message .= 'Въведеният SEF URL е невалиден<br/>';
			
		$sql = "SELECT
					album_id
				FROM
					album
				WHERE
					sef_url = '".$_POST['sef_url']."'
					
					AND album_id != '$id'
				  ";
		$result = query($sql);
		if ($row_seo = mysql_fetch_object($result)) $error_message .= 'Този SEF URL вече е използван! <br/>';
		
	
		//ОК
		if(!$error_message) {
			
			$sql = "UPDATE album SET
				  sef_url = '".escape($_POST['sef_url'])."',
				  published = '".intval($_POST['published'])."'

				 WHERE
				 album_id = '$id'
				";
		query($sql);

		$sql = 'SELECT lang_id,Name,code
				FROM
				language
				WHERE
				published
					';
		$result_lang = query($sql);
		
		while ($row_lang = mysql_fetch_object($result_lang)) {
			
				$em = $row_lang->lang_id;
				eval('$title =  $_POST[\'title_'.$em.'\'];');
				
			
			$sql = "UPDATE album_description SET
				  
				   title = '".escape($title)."'
				   
				WHERE
					album_id = '$id'
					AND
					lang_id = '$em'
				  ";
				 
		query($sql);
		}
			
			// Връзка с категория
			if($_POST['category_id'])
			{
				$sql = "DELETE FROM 
				   album_to_category
				WHERE
				   album_id = '$id'
				 ";
					query($sql);
			
			
				$category_id = $_POST['category_id'];
			  
				foreach ($category_id as $key => $value) {
				
					$sql = 'INSERT INTO album_to_category
								  (album_id,category_id)
								VALUES
								  ('.$id.','.intval($value).')
								  ';
					query($sql);
				
				}
			}
			
			// Връзка с фотограф
			if($_POST['photographer_id'])
			{
				$sql = "DELETE FROM 
				   album_to_photographer
				WHERE
				   album_id = '$id'
				 ";
					query($sql);
			
				$photographer_id = $_POST['photographer_id'];
			  
				foreach ($photographer_id as $key => $value) {
				
					$sql = 'INSERT INTO album_to_photographers
								  (album_id,photographer_id)
								VALUES
								  ('.$id.','.intval($value).')
								  ';
					query($sql);
				
				}
			}
	
			
			
			$_SESSION['message'] .= 'Промените са запазени успешно!';
			redirect('album_edit.php?album_id='.$id);
			 
			
		}

}
  	
	head_admin("Редактиране на албум");
	
	if(!$_POST['is_submitted'])
	{
	$sql = "SELECT * FROM
						album
					WHERE
						album_id = '$id'
					";
					$result = query($sql);
					$row = mysql_fetch_assoc($result);
					$_POST = $row;
	}
?>





	<?php if ($error_message) { ?>

	<div class="message red">
	<h3>Грешка!</h3>
	<?=$error_message?>
	</div>
	<?php } ?>
    
     <?php if ($_SESSION['message']) { ?>
			<div class="message green">
				
				<?=$_SESSION['message']?>
			</div>
		<?php 
            unset($_SESSION['message']);
        } ?>
            
    <div class="topbuttons"> <a href="<?=$redirect?>">Обратно</a> </div>
    <h3>Редактиране на албум</h3>
    <form  id="album_new_form_id" action="<?=$_SERVER['PHP_SELF']?>?album_id=<?=$id?>" method="post" enctype="multipart/form-data">
		<input type="hidden" name="is_submitted" value="1" />
		<input type="hidden" name="redirect" value="<?=$redirect?>" />
		<input id="redirectForm" type="hidden" name="redirectForm" value="" />
		<dt><label class="required">Линк :</label>
        <?=HTML_BASE?>album/<input id="sef_url" name="sef_url" type="text" value="<?=$_POST['sef_url']?>" >
        </dt>
        <!-- Tabs beginning-->           
     	
		<dl>
        	<ul id="tabs-ui"></ul>
			
   
 		 <?php 
			
			$sql = 'SELECT lang_id,Name,code
					FROM language
					WHERE published';
			$result = query($sql);
			
			$i=0;
			$tabs="";
			while ($row_lang = mysql_fetch_object($result)) {
				$em = $row_lang->lang_id;
				/*$tabs.='<li><a href="'.$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'].'#tabs-'.$em.'">'.$row_lang->Name.'</a></li>';
				*/
					$sql_d = "SELECT *	
					FROM
						album_description
					WHERE
						album_id = '$id'
						AND lang_id = '$em'
					
					";
					$result_cat_d = query($sql_d);
					$row_cat_d = mysql_fetch_object($result_cat_d);
					$title = $row_cat_d->title;
					
					
					
				if ($_POST['is_submitted']) {
				
				eval('$title =  $_POST[\'title_'.$em.'\'];');
				
				}
				
				  
			?>
            
  			
  					
    				<dt>
      					<label class="required">Заглавие на <?=$row_lang->Name?></label>
					</dt>
                    
    				<dd> 
     					 <input class="inputbox w500" name="title_<?=$row_lang->lang_id?>" type="text" value="<?=$title?>" >
					</dd>
                    
					
		
		<?php
            $i++;
            }
        ?>
		</dl>
        
 		<dl style="float:left; width:45%; margin-right:2%">
   			<dt>
      			<label >Категория</label>
    		</dt>
    		<dd>
				<ul class="type-box">
				<?php         
                    $sql_c = "SELECT
                    c.category_id,
                    d.Name
                    
                FROM
                    category AS c,
                    category_description AS d
                WHERE
                
                    c.category_id = d.category_id
                    
                    AND
                    
                    d.lang_id = '1'
                    
                    AND
                    c.published
                    
                    ORDER BY c.order_number DESC
                    
                  ";
                
                    $result_c = query($sql_c);
                    $i = 1;	
                    while ($row = mysql_fetch_object($result_c)) {
                          ?>
                        <li>
                          <label>
                            <input class="checkbox" name="category_id[<?=$i?>]" type="checkbox" value="<?=$row->category_id?>" 
							<?php if($_POST["category_id"]){ ?>
                                        <?=(($row->category_id == $_POST["category_id"][$i])?"checked=\"checked\"":"")?> 
                                        <?php
                                        }else{
                                $sql_check = "SELECT category_id FROM album_to_category WHERE album_id = '".$id."' AND category_id = '".($row->category_id)."'";
                                $n = mysql_numrows(query($sql_check));
                                
                                if($n)echo "checked=\"checked\"";
                                        }
                                ?> /><?=$row->Name?> </label>
                        </li>
        			<?php $i++; } ?>
				</ul>
			</dd>
		</dl>
		
        
        <dl style="float:left; width:48%;">
   			<dt>
      			<label >Фотограф</label>
    		</dt>
    		<dd>
				<ul class="type-box">
				<?php         
                    $sql_c = "SELECT
                    c.photographers_id,
                    d.title
                    
                FROM
                    photographers AS c,
                    photographers_description AS d
                WHERE
                
                    c.photographers_id = d.photographers_id
                    
                    AND
                    
                    d.lang_id = '1'
                    
                    AND
                    c.published
                    
                    ORDER BY c.order_number DESC
                    
                  ";
                
                    $result_c = query($sql_c);
                    $i = 1;	
                    while ($row = mysql_fetch_object($result_c)) {
                          ?>
                        <li>
                          <label>
                            <input class="checkbox" name="photographer_id[<?=$i?>]" type="checkbox" value="<?=$row->photographers_id?>" 
                                        <?php if($_POST["photographers_id"]){ ?>
                                        <?=(($row->photographers_id == $_POST["photographers_id"][$i])?"checked=\"checked\"":"")?> 
                                        <?php
                                        }else{
                                $sql_check = "SELECT photographers_id FROM album_to_photographers WHERE album_id = '".$id."' AND photographers_id = '".($row->photographers_id)."'";
                                $n = mysql_numrows(query($sql_check));
                                
                                if($n)echo "checked=\"checked\"";
                                        }
                                ?> /><?=$row->title?></label>
                        </li>
        			<?php $i++; } ?>
				</ul>
			</dd>
		</dl>
        
        
        
        <dl>
			
		
			<label>
				<input class="checkbox" name="published" id="published" type="checkbox" value="1" <?=(($_POST['published'])?"checked=\"checked\"":"")?> />
    Публикуван</label>
    
    	</dl>
	
     <input type="submit" name="submit" id="submit" class="button" value="Запиши">
	
    </form>
		
<br>
<br>
<br>

<h3>Снимки</h3>
<br>


<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<!-- blueimp Gallery styles -->
<link rel="stylesheet" href="http://blueimp.github.io/Gallery/css/blueimp-gallery.min.css">
<!-- CSS to style the file input field as button and adjust the Bootstrap progress bars -->
<link rel="stylesheet" href="css/jquery.fileupload-ui.css">
<!-- CSS adjustments for browsers with JavaScript disabled -->
<noscript><link rel="stylesheet" href="css/jquery.fileupload-ui-noscript.css"></noscript>
  <!-- The file upload form used as target for the file upload widget -->
    <form id="fileupload" action="uploads/" method="POST" enctype="multipart/form-data">
        
       <div class="row fileupload-buttonbar" >
            <div class="col-lg-8">
                <!-- The fileinput-button span is used to style the file input field as button -->
                <span class="btn btn-success fileinput-button">
                    <i class="icon-plus icon-white"></i>
                    <span>Избери файлове...</span>
                    <input type="file" name="files[]" multiple>
                </span>
                <button type="submit" class="btn btn-primary start">
                    <i class="icon-upload icon-white"></i>
                    <span>Качи всички</span>
                </button>
                <button type="reset" class="btn btn-warning cancel">
                    <i class="icon-ban-circle icon-white"></i>
                    <span>Спри качването</span>
                </button>
                <button type="button" class="btn btn-danger delete">
                    <i class="icon-trash icon-white"></i>
                    <span>Изтрий избраните</span>
                </button>
                <label>
				<input type="checkbox" class="toggle"> Избери всички</label>
                <!-- The loading indicator is shown during file processing -->
                <span class="fileupload-loading"></span>
            </div>
            <!-- The global progress information -->
            <div class="col-lg-4 fileupload-progress">
                <!-- The global progress bar -->
                <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100">
                    <div class="progress-bar progress-bar-success" style="width:0%;"></div>
                </div>
                <!-- The extended global progress information -->
                <div class="progress-extended">&nbsp;</div>
            </div>
        </div>
		
		
		
        <!-- The table listing the files available for upload/download -->
        <table role="presentation" class="table table-striped"><tbody class="files"></tbody></table>
    </form>
    

<!-- The blueimp Gallery widget -->
<div id="blueimp-gallery" class="blueimp-gallery blueimp-gallery-controls" data-filter=":even">
    <div class="slides"></div>
    <h3 class="title"></h3>
    <a class="prev">‹</a>
    <a class="next">›</a>
    <a class="close">×</a>
    <a class="play-pause"></a>
    <ol class="indicator"></ol>
</div>
<!-- The template to display files available for upload -->
<script id="template-upload" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}

    <tr class="template-upload">
        <td>
            <span class="preview"></span>
        </td>
        <td>
            <p class="name">{%=file.name%}</p>
            {% if (file.error) { %}
                <div><span class="label label-danger">Note</span> {%=file.error%}</div>
            {% } %}
        </td>
        <td>
            <p class="size">{%=o.formatFileSize(file.size)%}</p>
            {% if (!o.files.error) { %}
                <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><div class="progress-bar progress-bar-success" style="width:0%;"></div></div>
            {% } %}
        </td>
        <td>
            {% if (!o.files.error && !i && !o.options.autoUpload) { %}
                <button class="btn btn-primary start">
                    <i class="icon-upload icon-white"></i>
                    <span>Качи</span>
                </button>
            {% } %}
            {% if (!i) { %}
                <button class="btn btn-warning cancel">
                    <i class="icon-ban-circle icon-white"></i>
                    <span>Премахни</span>
                </button>
            {% } %}
        </td>
    </tr>
{% } %}
</script>
<!-- The template to display files available for download -->
<script id="template-download" type="text/x-tmpl">

{% for (var i=0, file; file=o.files[i]; i++) { %}
    <tr class="template-download">
        <td >
            <span class="preview" >
                {% if (file.thumbnailUrl) { %}
                    <a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" data-gallery><img style=" width:120px;" src="{%=file.thumbnailUrl%}"></a>
                {% } %}
            </span>
        </td>
        <td>
            <p class="name">
                {% if (file.url) { %}
                    <a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" {%=file.thumbnailUrl?'data-gallery':''%}>{%=file.name%}</a>
                {% } else { %}
                    <span>{%=file.name%}</span>
                {% } %}
            </p>
            {% if (file.error) { %}
                <div><span class="label label-danger">Note</span> {%=file.error%}</div>
            {% } %}
			<span class="size">{%=o.formatFileSize(file.size)%}</span>
        </td>
        <td width="300">
		
            <label>Описание BG</label>
			<input id="id_{%=file.name%}_1" onchange="inputtexts('{%=file.name%}','1',this.value)" class="inputbox w250"  type="text" value="" >
			
			<label>Описание EN</label>
			<input id="id_{%=file.name%}_2" onchange="inputtexts('{%=file.name%}','2',this.value)" class="inputbox w250"  type="text" value="" >
		
        </td>
        <td>
            {% if (file.deleteUrl) { %}
                <button class="btn btn-danger delete" data-type="{%=file.deleteType%}" data-url="{%=file.deleteUrl%}"{% if (file.deleteWithCredentials) { %} data-xhr-fields='{"withCredentials":true}'{% } %}>
                    <i class="glyphicon glyphicon-trash"></i>
                    <span>Изтрий</span>
                </button>
                <input  type="checkbox" name="delete" value="1" class="toggle">
            {% } else { %}
                <button class="btn btn-warning cancel">
                    <i class="glyphicon glyphicon-ban-circle"></i>
                    <span>Премахни</span>
                </button>
            {% } %}
        </td>
    </tr>
{% } %}

</script>
<!-- The jQuery UI widget factory, can be omitted if jQuery UI is already included -->
<script src="js/vendor/jquery.ui.widget.js"></script>
<!-- The Templates plugin is included to render the upload/download listings -->
<script src="js/blueimp/tmpl.min.js"></script>
<!-- The Load Image plugin is included for the preview images and image resizing functionality -->
<script src="js/blueimp/load-image.all.min.js"></script>
<!-- The Canvas to Blob plugin is included for image resizing functionality -->
<script src="js/blueimp/canvas-to-blob.min.js"></script>
<!-- blueimp Gallery script -->
<script src="js/blueimp/jquery.blueimp-gallery.min.js"></script>
<!-- The Iframe Transport is required for browsers without support for XHR file uploads -->
<script src="js/jquery.iframe-transport.js"></script>
<!-- The basic File Upload plugin -->
<script src="js/jquery.fileupload.js"></script>
<!-- The File Upload processing plugin -->
<script src="js/jquery.fileupload-process.js"></script>
<!-- The File Upload image preview & resize plugin -->
<script src="js/jquery.fileupload-image.js"></script>
<!-- The File Upload audio preview plugin -->
<script src="js/jquery.fileupload-audio.js"></script>
<!-- The File Upload video preview plugin -->
<script src="js/jquery.fileupload-video.js"></script>
<!-- The File Upload validation plugin -->
<script src="js/jquery.fileupload-validate.js"></script>
<!-- The File Upload user interface plugin -->
<script src="js/jquery.fileupload-ui.js"></script>
<!-- The main application script -->
<script src="js/main.js"></script>
<!-- The XDomainRequest Transport is included for cross-domain file deletion for IE 8 and IE 9 -->
<!--[if (gte IE 8)&(lt IE 10)]>
<script src="js/cors/jquery.xdr-transport.js"></script>
<![endif]-->

<div id="mess"></div>

<script >

	<?php
		
		$sql_imds = "SELECT * FROM
						album_images_description
					WHERE
						album_id = '$id'
					";
		$result_imds = query($sql_imds);
		$ids = '';
		$desc = '';
		while($imds = mysql_fetch_object($result_imds))
		{
			$desc .= '"'.escape($imds->description).'",';
			
			$ids .= '"id_'.$imds->image.'_'.$imds->lang_id.'",';
			
	}
	$desc = substr($desc, 0, -1);
	$ids = substr($ids, 0, -1);
	?>
	var ids = new Array(<?=$ids?>);
	var desc = new Array(<?=$desc?>);
	
	var inter =setInterval(function(){loadDescriptions()},800);
	 function loadDescriptions()
	 {
		 clearInterval(inter);
		 for(var i =0; i < ids.length; i++)
		 {
			 var id = ids[i].replace(".","\\.")
			 $('#'+id).val(desc[i]);
			 
		 }
	 }
	
 function inputtexts(file,lang,content){
	 var album = '<?=$_GET['album_id']?>';
	 
	 $.ajax({
		type: "POST",
		url: "add_image_title.php",
		data: "album=" + album + "&file="+ file + "&lang="+ lang + "&description=" + content,
		success: function(msg){
			$("#mess").html(msg);
			$("#mess").slideDown('fast', function(){
				$(this).delay(4000).slideUp();
			});
		},
		error: function(msg){
			$("#mess").html(msg);
			$("#mess").addClass('red');
			$("#mess").slideDown('fast', function(){
				$(this).delay(4000).slideUp();
			});
			
		}
	});
 }

</script>

<?php
	foot_admin(); 
?>
